package com.example.bigdata.scala.文件

import java.io.{File, FileWriter, PrintWriter}

import scala.io.Source

object IODemo {

  def main(args: Array[String]): Unit = {
    val filename = "/Users/hrsjw1/Downloads/tmp/dc_es_del.list"
    readFile_01(filename)
    println("\n")
    readFile_02(filename)
    println("\n")
    readFile_03(filename)
    println("\n")
    writeFile(filename,"./output.txt")
    println("\n")
    readFile_04(filename)

  }

  def readFile_01 (filename : String): Unit ={
    val sourceFile = Source.fromFile(filename,"UTF-8")
    val lineIterator = sourceFile.getLines()
    println(lineIterator.hasNext)
    /*for(line <- lineIterator)
      println(line)*/
  }

  def readFile_02(filename : String): Unit ={
    val sourceFile = Source.fromFile(filename,"UTF-8")
    val lines = sourceFile.getLines().toArray
    println(lines.head)
    //for(line <- lines) println(line)
  }
  def readFile_03(filename:String): Unit = {
    val sourceFile = Source.fromFile(filename,"UTF-8")
    val lines = sourceFile.mkString
    println(lines)
    //println(lines.head)

  }
  def readFile_04(filename:String): Unit = {
    val sourceFile = Source.fromFile(filename,"UTF-8")
    val ll  = {
      sourceFile.getLines()
        .toList
        .filter(_.trim != "")
        .filter(_.endsWith("0"))
    }
    println("\nll : \n" + ll)

  }

  def writeFile (input :String,output :String): Unit ={
    val sourceFile = Source.fromFile(input,"UTF-8")
    val writeFile = new PrintWriter(new File(output))
    for(line <- sourceFile.getLines()){
      //println("write > " + line)
      writeFile.println(line)

    }
    writeFile.write("+++++ OK !")
    writeFile.close()

    //new File  不能追加内容
    //new FileWriter（filename,append）

    val w1 = new PrintWriter(new FileWriter("./printWriter.txt",true))
    w1.println("1111")
    w1.write("zzzz\n")
    w1.write("xxx\n")
    w1.println("yyy\n")
    w1.close()
  }
}
